const sleep = async (delay = 0) => {
    return await new Promise((r) => setTimeout(r, delay));
};

class TaskRunner {
    constructor(options = {}) {
        // 参数校验
        if (!Array.isArray(options.tasks)) {
            throw new Error('Tasks must be an array');
        }
        if (typeof options.runTask !== 'function') {
            throw new Error('runTask must be a function');
        }

        // 配置参数
        this.tasks = options.tasks;
        this.runTask = options.runTask;
        this.preDelay = options.preDelay || 100;
        this.postDelay = options.postDelay || 100;
        this.maxRetries = options.maxRetries || 3;

        // 状态初始化
        this.index = options.startIndex || 0;
        this.status = 'idle';
        this.retryCount = 0;
        this.pendingResolve = null;

        // 事件回调
        this.eventHandlers = {
            onStart: options.onStart,
            onPause: options.onPause,
            onResume: options.onResume,
            onStop: options.onStop,
            onTaskComplete: options.onTaskComplete,
            onError: options.onError,
            onRetry: options.onRetry
        };
    }

    async start() {
        if (this.status !== 'idle') return;

        this._triggerEvent('onStart');
        this.status = 'playing';
        this._run();
    }

    async _run() {
        while (this.status === 'playing') {
            try {
                // Pre-delay
                await sleep(this.preDelay);

                // 执行任务（带重试机制）
                let result;
                for (this.retryCount = 0; this.retryCount <= this.maxRetries; this.retryCount++) {
                    try {
                        result = await this.runTask(this.tasks[this.index]);
                        if (result) break;

                        if (this.retryCount < this.maxRetries) {
                            this._triggerEvent('onRetry', this.retryCount + 1);
                            await sleep(this.postDelay); // 重试间隔
                        }
                    } catch (error) {
                        if (this.retryCount === this.maxRetries) throw error;
                    }
                }

                // 处理最终结果
                if (!result) {
                    this.status = 'error';
                    this._triggerEvent('onError', `Task failed after ${this.maxRetries} retries`);
                    return;
                }

                // 任务成功
                this._triggerEvent('onTaskComplete', this.index);
                this.index++;

                // Post-delay
                await sleep(this.postDelay);
            } catch (error) {
                this.status = 'error';
                this._triggerEvent('onError', error.message);
                return;
            }

            // 检查暂停状态
            if (this.pendingResolve) {
                const shouldContinue = await new Promise(resolve => {
                    this.pendingResolve = resolve;
                });
                if (!shouldContinue) return;
            }
        }
    }

    pause() {
        if (this.status !== 'playing') return;

        this.status = 'paused';
        this._triggerEvent('onPause');
        this.pendingResolve = () => { }; // 初始化pendingResolve
    }

    resume() {
        if (this.status !== 'paused') return;

        this.status = 'playing';
        this._triggerEvent('onResume');
        if (this.pendingResolve) {
            this.pendingResolve(true);
            this.pendingResolve = null;
        }
    }

    stop() {
        this.status = 'stopped';
        this._triggerEvent('onStop');
        if (this.pendingResolve) {
            this.pendingResolve(false);
            this.pendingResolve = null;
        }
    }

    _triggerEvent(eventName, ...args) {
        if (this.eventHandlers[eventName]) {
            try {
                this.eventHandlers[eventName](...args);
            } catch (error) {
                console.error(`Error in ${eventName} handler:`, error);
            }
        }
    }
}

module.exports = TaskRunner;